package com.manda.smart.hub.common.concurrent;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.hutool.core.util.ClassUtil;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author hongda.li
 */
public final class ConcurrentTimeMillis {
    /**
     * 当前的时间戳
     */
    private static volatile long timestamp = System.currentTimeMillis();

    private static final ScheduledThreadPoolExecutor EXECUTOR;

    // 设置一个定时任务，每毫秒更新一次时间戳
    static {
        EXECUTOR = new ScheduledThreadPoolExecutor(1, ThreadFactoryBuilder.create()
                .setDaemon(true)
                .setNamePrefix(ClassUtil.getShortClassName(ConcurrentTimeMillis.class.getName()))
                .build());
        EXECUTOR.scheduleAtFixedRate(() -> ConcurrentTimeMillis.timestamp = System.currentTimeMillis(),
                1,
                1,
                TimeUnit.MILLISECONDS);
    }

    private ConcurrentTimeMillis() {
    }

    /**
     * 获取当前的毫秒数
     *
     * @return 当前的毫秒数
     */
    public static long get() {
        return timestamp;
    }
}
